<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v5;

use app\api\controller\v2\Auth;
use app\api\controller\v9\OrdersPay;
use app\common\lib\exception\ApiException;
use app\common\lib\Orders as OrdersLib;
use app\common\model\Orders as OrdersModel;
use app\common\model\Recode;
use think\Db;
use think\Log;

/**
 * 获取运势商品信息和运势下单
 * Class FortuneForGoods
 * @package app\api\controller\v5
 */
class Orders extends Auth
{
    protected $nodel;
    private $acg_gids;
    private $fortune_gids;
    protected $msg;

    public function _initialize()
    {
        parent::_initialize();

        $this->acg_gids = config('goods.acg_id');
        $this->fortune_gids = config('goods.fortune_id');
        $this->nodel = config('code.nodel');
    }

    /**
     * 订单列表
     * @return \think\response\Json
     * @throws ApiException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $type = input('get.type/d', 0);

        $page = input('get.page/d', 1);

        $uid = $this->user['id'];

        // 判断订单是否超时未支付
        check_overtime($uid);

        $OrdersModel = new OrdersModel();
        $RecodeModel = new Recode();

        $orders = $OrdersModel->getUidOrders(['uid' => $uid, 'type' => $type, 'is_del' => $this->nodel, 'page' => $page]);

        // 将数据根据创建时间排序
        array_multisort(array_column($orders, 'create_time'), SORT_NUMERIC, SORT_DESC, $orders);

        // 重组订单数据
        $start_time = '';
        $end_time = '';

        $data = [];

        if ($orders || !empty($orders))
        {
            foreach ($orders as $k => $v)
            {
                if (isset($v['type']) && $v['type'])
                {
                    switch ($v['type'])
                    {
                        case 1:
                            $format = 'Y-m-d';
                            break;
                        case 2:
                            $format = 'Y-m';
                            break;
                        case 3:
                            $format = 'Y';
                            break;
                        default:
                            $format = '';
                            break;
                    }
                    $start_time = date($format, $v['time']);
                    /**
                     * 有效时间最小单位为日，所以只需要往前推一天就是结束日期
                     */
                    $end_time = date($format, strtotime($v['expire_time'], $v['time']) - 86400);
                }

                $or_price = sprintf("%.2f", $v['or_prize']);
                $now_price = sprintf("%.2f", $v['now_prize']);
                $total_amount = sprintf("%.2f", $v['total_amount']);
                $create_time = date('Y-m-d H:i:s', $v['create_time']);

                //商品活动折扣
                $activeDiscount = active($v['gid']);
                if ($activeDiscount['discount'] && !$this->is_apple_pay)
                {
                    $now_price *= $activeDiscount['discount'];
                }

                //校准生辰订单数据
                if ($v['gid'] == 1)
                {
                    if ($this->is_apple_pay)
                    {
                        $or_price = $this->apple_goods['rec_goods']['or_prize'];
                        $now_price = $this->apple_goods['rec_goods']['now_prize'];
                    }

                    $data[] = [
                        'type' => 1,
                        'rectification_data' => [
                            'id' => $v['reid'],
                            'birth' => date('Y-m-d', $v['start_time']),
                            'start_time' => date('H:i', $v['start_time']),
                            'end_time' => ((date('d', $v['start_time']) != date('d', $v['end_time'])) ? '次日' : '') . date('H:i', $v['end_time']),
                            'or_prize' => $or_price,
                            'now_prize' => $now_price,
                        ],
                        'status' => $v['restatus'] ?? 0,//校准生辰缓存字段不存在时，默认未支付
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                        'total_price' => $total_amount,
                    ];
                }//运势订单数据(运势)
                elseif (in_array($v['gid'], $this->fortune_gids))
                {
                    $a[] = $v;
                    $array = [];
                    $rids_array = explode(',', $v['rids']);
                    foreach ($rids_array as $kk => $vv)
                    {
                        if ($vv)
                        {
                            try
                            {

                                $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $vv]);

                            }
                            catch (\Exception $e)
                            {

                                $rname = [
                                    'id' => $vv,
                                    'name' => '未找到',
                                ];
                                \think\Log::write('异常档案id：' . $vv, 'error', true);
                            }
                        } else
                        {
                            $rname = [
                                'id' => $vv,
                                'name' => '未找到',
                            ];
                        }

                        if ($this->is_apple_pay)
                        {
                            foreach ($this->apple_goods['fortune_goods'] as $fortune_day_good)
                            {
                                if ($fortune_day_good['id'] == $v['gid'])
                                {
                                    $or_price = $fortune_day_good['or_prize'];
                                    $now_price = $fortune_day_good['now_prize'];
                                }
                            }
                        } else
                        {
                            //商品活动折扣
                            $activeDiscount = active($v['gid']);
                            if ($activeDiscount['discount'] && !$this->is_apple_pay)
                            {
                                $now_price = sprintf("%.2f", $v['now_prize'] * $activeDiscount['discount']);
                            }
                        }

                        $array[] = [
                            'id' => $rname['id'],
                            'gid' => $v['gid'],
                            'rname' => $rname['name'],
                            'fortune_type' => $v['type'],
                            'start_time' => $start_time,
                            'end_time' => $end_time,
                            'or_price' => $or_price,
                            'now_price' => $now_price,
                        ];
                    }
                    $data[] = [
                        'type' => 2,
                        'fortune_data' => $array,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => count($array),
                        'total_price' => $total_amount,
                    ];

                }//命格线订单数据
                elseif (in_array($v['gid'], $this->acg_gids))
                {
                    $gname = [];

                    try
                    {

                        $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $v['rid']]);

                    }
                    catch (\Exception $e)
                    {

                        $rname = [
                            'name' => '未找到',
                        ];
                        \think\Log::write('异常档案id：' . $v['rid'], 'error', true);
                    }

                    try
                    {
                        $ogoods = Db::table('app_orders_goods')
                            ->alias('og')
                            ->join('app_goods g', 'og.gid=g.id', 'LEFT')
                            ->field('g.name')
                            ->where(['og.oid' => $v['oid']])
                            ->selectOrFail();

                    }
                    catch (\Exception $e)
                    {

                        \think\Log::write('异常订单id：' . $v['oid'], 'error', true);

                        return show(config('code.error'), '订单异常');
                    }

                    foreach ($ogoods as $i => $g)
                    {
                        $gname[] = $g['name'];
                    }

                    if (in_array($v['status'], [1, 4]))
                    {
                        $line_status = 1;
                    } else
                    {
                        $line_status = $v['status'];
                    }

                    $data[] = [
                        'type' => 3,
                        'acgmap_data' => [
                            'order_name' => '幸运之城',
                            'order_sub_name' => '幸运之城解锁',
                            'order_sub_rname' => $rname['name'],
                            'order_sub_names' => implode(',', $gname),
                        ],
                        'total_price' => $total_amount,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $line_status,
                        'trade_type' => $v['trade_type'],
                        'count' => count($ogoods),
                    ];

                }
            }
        }


        // 统计有多少订单
        $total = count($data);
        //获取数据分页信息
        $per_page = 20;// 当前订单订单每页显示数量
        $data_list = getPaginatorData($total, $page, $per_page);
        //获取分页后的数据
        $data_list['data'] = array_slice($data, $data_list['start'], $per_page);
        unset($data_list['start']);
        unset($data_list['end']);

        return show(config('code.success'), '加载成功', $data_list);
    }

    /**
     * 订单详情
     * @return \think\response\Json
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->param();

        $validate = validate('Orders');

        //验证请求参数
        if ($validate->scene('read')->check($param) !== true)
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $order_id = $param['order_id'];

        //支付客户端判断该订单是否已经支付,若已经支付,但是status=0;就更改status=1
        (new OrdersLib())->validateOrders($order_id);
        $where = ['or.is_del' => $this->nodel, 'order_id' => ['eq', $order_id]];

        $field = 'or.uid,or.status,or.fid,or.create_time,or.order_id,or.trade_type,or.gid,or.total_amount,or.pay_time,or.return_time,go.name,go.or_prize,go.now_prize,go.expire_time gtime,fr.id,fr.rids,fr.time ftime,fr.type';

        $OrdersModel = new OrdersModel();
        $RecodeModel = new Recode();

        try
        {
            $data = $OrdersModel
                ->alias('or')
                ->field($field)
                ->join('app_goods go', 'or.gid=go.id', 'LEFT')
                ->join('app_fortune fr', 'or.fid=fr.id', 'LEFT')
                ->where($where)
                ->findOrFail();
            $data = json_decode(json_encode($data, true), true);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '订单未找到');
        }

        if ($data['uid'] != $this->user['id'])
        {
            Log::write('非法订单查询：' . json_encode($param, true), 'error', true);
            return show(config('code.error'), '服务异常，请稍后重试～');
        }
        switch ($data['type'])
        {
            case 1:
                $start_time = date('Y-m-d', $data['ftime']);
                $end_time = date('Y-m-d', strtotime($data['gtime'], $data['ftime']) - 86400);
                break;
            case 2:
                $start_time = date('Y-m', $data['ftime']);
                $end_time = date('Y-m', strtotime($data['gtime'], $data['ftime']) - 86400);
                break;
            case 3:
                $start_time = date('Y', $data['ftime']);
                $end_time = date('Y', strtotime($data['gtime'], $data['ftime']) - 86400);
                break;
            default :
                return show(config('code.error'), '订单详情获取失败');
        }
        $arr['status'] = $data['status'];

        foreach (explode(',', $data['rids']) as $k => $v)
        {
            $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $v]);

            if ($this->is_apple_pay)
            {
                foreach ($this->apple_goods['fortune_goods'] as $ap)
                {
                    if ($ap['id'] == $data['gid'])
                    {
                        $or_price = $ap['or_prize'];
                        $now_price = $ap['now_prize'];
                    }
                }
            } else
            {
                $or_price = $data['or_prize'];
                $now_price = $data['now_prize'];
                //商品活动折扣
                $activeDiscount = active($data['gid']);
                if ($activeDiscount['discount'] && !$this->is_apple_pay)
                {
                    $now_price *= $activeDiscount['discount'];
                }
            }

            $arr['fortune'][] = [
                'id' => $rname['id'],
                'gid' => $data['gid'],
                'rname' => $rname['name'],
                'fortune_type' => $data['type'],
                'start_time' => $start_time,
                'end_time' => $end_time,
                'or_price' => $or_price,
                'now_price' => sprintf('%.2f', $now_price),
            ];
        }

        $arr['count'] = count(explode(',', $data['rids']));

        $arr['or_total_price'] = sprintf("%.2f", $arr['count'] * $data['or_prize']);
        $arr['total_price'] = sprintf("%.2f", $data['total_amount']);
        $arr['trade_type'] = $data['trade_type'];
        $arr['order_id'] = $order_id;
        $arr['create_time'] = date('Y-m-d H:i:s', (int)($data['create_time']));

        if ($data['pay_time'])
        {
            $arr['order'][] = [
                'name' => "支付时间",
                'value' => date('Y-m-d H:i:s', (int)($data['pay_time'])),
            ];

        }
        if ($data['return_time'])
        {
            $arr['order'][] = [
                'name' => "退款时间",
                'value' => date('Y-m-d H:i:s', (int)($data['return_time'])),
            ];
        }

        return show(200, '成功', $arr);
    }

    /**
     * 解锁所有运势,运势下单
     * @return \think\response\Json
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function pay_unlock()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param['rids'] = input('param.rids/s', '');
        $param['time'] = input('param.time/s', '');
        $param['trade_type'] = input('param.trade_type/d', 0);
        $param['gid'] = input('param.gid/d', 0);
        $param['fortune_type'] = input('param.fortune_type/d', 0);
        $this->CheckUnlock($param);
        if ($this->msg)
        {
            Log::write('v5解锁运势请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }

        $validate = validate('Orders');

        if ($validate->scene('v5_pay_unlock')->check($param) !== true)
        {
            return show(config('code.error'), json_encode($validate->getError(), true));
        }

        // 支付方式
        $trade_type = $param['trade_type'];
        // 商品类型id   1=>校准生辰
        $gid = $param['gid'];
        // 选择的档案id，字符串
        $rids = $param['rids'];
        // 选择的解锁日期,字符串类型
        $start_time = $param['time'];
        //运势类型id
        $fortune_type = $param['fortune_type'];
        // openid
        $openid = input('param.openid', '');
        // pay-redirect-url
        $callback_url = input('param.callback_url', '');

        switch (true)
        {
            case in_array($gid, config('goods.day_id')):
                $order_type = 2;
                break;
            case in_array($gid, config('goods.month_id')):
                $order_type = 3;
                break;
            case in_array($gid, config('goods.year_id')):
                $order_type = 4;
                break;
            default :
                return show(config('code.error'), '未知商品');
        }

        //下单统一
        $OrderPayModel = new OrdersPay();
        $data = $OrderPayModel->pay_unlock(['order_type' => $order_type, 'trade_type' => $trade_type, 'gid' => $gid, 'fortune_type' => $fortune_type, 'rids' => $rids, 'start_time' => $start_time, 'openid' => $openid, 'callback_url' => $callback_url]);

        if ($data && isset($data['status']) && $data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);
        }
        return show(config('code.error'), '下单失败', $data['data']);
    }

    /**
     * 检测下单参数
     * @param $param
     * @return string
     * @throws \Exception
     */
    private function CheckUnlock($param)
    {
        $this->msg = '';
        $gids = [];
        $config_goods = config('goods');
        if (!$param['rids'])
        {
            return $this->msg = '缺少档案信息';
        }
        $recodes = (new \app\common\cachemodel\Recode())->batchGetInfoByIds($param['rids']);
        foreach ($recodes as $recode)
        {
            if ($recode['uid'] != $this->user['id'])
            {
                return $this->msg = '服务异常';
            }
        }
        if (!$param['time'])
        {
            return $this->msg = '请选择时间';
        }
        //若不是支付宝或微信则退出
        if (!in_array($param['trade_type'], [1, 2], true))
        {
            return $this->msg = '未知的支付方式';
        }
        //fortune_type 1=>日运,2=>月运,3=>年运
        if (!in_array($param['fortune_type'], [1, 2, 3], true))
        {
            return $this->msg = '未知的商品';
        }
        if (!$param['gid'])
        {
            return $this->msg = '缺少商品信息';
        }
        //type=>1时,可不传gids
        if ($param['fortune_type'] === 1)
        {
            $gids = $config_goods['day_id'];
        }
        if ($param['fortune_type'] === 2)
        {
            $gids = $config_goods['month_id'];
        }
        if ($param['fortune_type'] === 3)
        {
            $gids = $config_goods['year_id'];
        }
        if (!in_array($param['gid'], $gids))
        {
            return $this->msg = '未知的商品';
        }
        return $this->msg;
    }
}
